package com.imut.controller;

import com.imut.entity.Novel;
import com.imut.entity.NovelImage;
import com.imut.service.NovelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * @Author jiangYaPeng
 * @Date 2025-07-08 16:34
 */
@RequestMapping(value = "/novel",method = {RequestMethod.GET})
@CrossOrigin(origins = {"*"}, maxAge = 3600)
@RestController
public class NovelController {

    @Autowired
    private NovelService novelService;


    @GetMapping("/novel")//title
    public ResponseEntity<List<Novel>> getNovelList(Novel novel) {
        return ResponseEntity.ok(novelService.selectAll(novel));
    }

    @GetMapping("/novel/{id}")//详情
    public ResponseEntity<Novel> getNovelById(@PathVariable Long id) {
        return ResponseEntity.ok(novelService.selectById(id));
    }

    @DeleteMapping("/novel/delete{id}")
    public ResponseEntity<Boolean> deleteNovelById(@PathVariable Long id) {
        return ResponseEntity.ok(novelService.deleteById(id));
    }

    @PostMapping("/novel/insert")
    public ResponseEntity<Boolean> insertNovelById(@RequestBody Novel novel) {
        return ResponseEntity.ok(novelService.insert(novel));
    }


    @PutMapping("/novel/update")
    public ResponseEntity<Boolean> updateNovelById(@RequestBody Novel novel) {
        return ResponseEntity.ok(novelService.update(novel));
    }

    @PostMapping("/uploadFile")
    public ResponseEntity<?> uploadFile(HttpSession session, MultipartFile myfile) {
        if (myfile == null || myfile.isEmpty()) {
            return ResponseEntity.badRequest().body("没有文件");
        }
        String uploadDir = "com/imut/userFiles";
        String projectRoot = System.getProperty("user.dir");
        String realPath = projectRoot + "/src/main/resources/" + uploadDir;


        String oldFileName = myfile.getOriginalFilename();

        File uploadFolder = new File(realPath);

        if (!uploadFolder.exists()) {
            boolean created = uploadFolder.mkdirs();
            if (!created) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("创建目录失败");
            }
        }
        // 4. 生成新的文件名称
        String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
        File newFile = new File(uploadFolder, newFileName);

        // 5. 将内存中的数据写入磁盘
        try {
            myfile.transferTo(newFile);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败");
        }

        // 6. 将文件信息保存到数据库
        NovelImage novelImage = new NovelImage();
        novelImage.setFileName(newFileName);
        novelImage.setFilePath(uploadDir + "/" + newFileName); // 保存相对路径
        novelService.insertUserFile(novelImage);

        // 7. 返回成功响应
        return ResponseEntity.ok("File uploaded successfully.");
    }


}
